package com.allen.framework.readwriterouter.datasource;

import com.allen.framework.readwriterouter.IDynamicSlaveDatasourceNLBStrategy;
import com.allen.framework.readwriterouter.strategy.DefaultDynamicSlaveDatasourceNLBStrategy;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Author: Allen
 * @Date: Created in 16:13 2019-08-28
 * @Description:
 */
@Slf4j
@Data
@Component
public class DynamicDatasourceHolder {

    /**
     * 负载策略接口
     */
    private IDynamicSlaveDatasourceNLBStrategy dynamicSlaveDatasourceNLBStrategy;

    public DynamicDatasourceHolder(@Nullable IDynamicSlaveDatasourceNLBStrategy dynamicSlaveDatasourceNLBStrategy) {
        this.dynamicSlaveDatasourceNLBStrategy = dynamicSlaveDatasourceNLBStrategy;
    }

    @PostConstruct
    public void init() {
        if (dynamicSlaveDatasourceNLBStrategy == null) {
            dynamicSlaveDatasourceNLBStrategy = new DefaultDynamicSlaveDatasourceNLBStrategy();
        }
    }

    /**
     * 保存着当前数据访问的数据源名称
     */
    private ThreadLocal<String> dynamicDatasourceRouterThreadLocal = new ThreadLocal<String>();

    /**
     * slave机器的key组
     */
    private List<String> slaveList;

    /**
     * 主服务器
     */
    private String master;


    public String getConcurrent() {
        return dynamicDatasourceRouterThreadLocal.get();
    }

    /**
     * 切换当前动态数据源为主数据源
     */
    public void nowMaster() {
        log.debug("dynamic datasource change to {}" ,master);
        dynamicDatasourceRouterThreadLocal.set(master);
    }

    /**
     * 切换当前数据源为slave数据源
     */
    public void nowSlave() {
        String slaveKey = dynamicSlaveDatasourceNLBStrategy.concurrentSlave(slaveList);
        log.debug("dynamic datasource change to {}" ,slaveKey);
        dynamicDatasourceRouterThreadLocal.set(slaveKey);
    }

}
